<template>
	<view>
    <uv-toast ref="uToast"></uv-toast>
    <uv-no-network></uv-no-network>
    <Nav title="商品详情"></Nav>
    <Header></Header>
    <view class="layout">
      <view class="content" v-for="(item,index) in good" :key="index">
        <view class="layout">
          <uv-image
              :src="item.goods_img"
              width="100%"
              height="300px"
          ></uv-image>
          <view class="info">
            <view class="price">￥{{item.goods_price}}</view>
            <view class="sale">{{item.deal_count}}</view>
          </view>
          <view class="title">{{item.goods_name}}</view>
          <view class="size">
            <view class="size-title">选择规格</view>
            <view class="size-list">
              <view class="box"
                    v-for="(item,index) in list"
                    :key="index"
                    :class="{ active: isActive(index) }"
                    @click="toggleActive(index)"
              >
                {{item}}
              </view>
            </view>
          </view>
        </view>
        <view class="btn">
          <uv-button text="加入购物车" type="primary"
                     custom-style="width: 150px"
                     @click="addCartFn"
          ></uv-button>
          <uv-button text="立即购买" type="primary"
                     @click="buyFn"
                     custom-style="width: 150px"
          ></uv-button>
        </view>
      </view>
    </view>
	</view>
</template>

<script setup>
import Header from "@/components/header.vue";
import Nav from "@/components/nav.vue";
import { ref, onMounted } from "vue";
import { GoodList, addCart } from "@/request/api";

const list = ['34', '35', '36', '37', '38', '39', '40'];
const activeIndex = ref(0);
const good = ref([]);
const pageNum = ref(1);
const goods = ref([]);
const id = ref(''); // 定义 id 为 ref

onMounted(() => {
  const pages = getCurrentPages(); // 获取当前页面栈
  const currentPage = pages[pages.length - 1]; // 获取当前页面
  id.value = currentPage.options.id;

  GoodList({ pageNum: pageNum.value, pageSize: 10 }) // 初始请求，获取商品列表
      .then(res => {
        if (res.code === 0) {
          const total = res.result.total; // 获取总数据量
          // 重新请求所有商品数据
          return GoodList({ pageNum: pageNum.value, pageSize: total });
        } else {
          console.error(res.msg); // 处理错误情况
        }
      })
      .then(res => {
        if (res && res.code === 0) {
          goods.value = res.result.list; // 获取所有商品列表

          // 查找当前商品
          good.value = goods.value.filter(item => {
            return item.id.toString() === id.value.toString(); // 确保类型一致
          });
          // console.log('当前商品:', good.value)
        }
      })
      .catch(err => {
        console.error('获取商品列表失败', err);
      });
});

const isActive = (index) => {
  return index === activeIndex.value; // 判断当前项是否为活动项
};

const toggleActive = (index) => {
  activeIndex.value = activeIndex.value === index ? -1 : index; // 切换活动状态
};

const addCartFn = () => {
  const goodsId = parseInt(id.value, 20);
  // console.log('商品 ID:', goodsId);
  const requestData = {
    goods_id: goodsId
  };

  addCart(requestData)
      .then(res => {
        // console.log('响应:', res);
        if (res.code === 0) {
          uni.showToast({
            title: "加入购物车成功"
          });
        } else {
          console.error('加入购物车失败:', res.msg || '未知错误');
          uni.showToast({
            title: res.msg || '加入购物车失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('请求出错:', err);
        uni.showToast({
          title: '请求错误',
          icon: 'none'
        });
      });
};

const buyFn = () => {
  goods.value.forEach(item => {
    item.number = 1; // Add number property directly
  });
  uni.setStorageSync("GOODS", good.value)
  // console.log(good.value, '当前商品列表')
  uni.navigateTo({
    url: '/pages/buy/buy'
  });
};
</script>

<style lang="scss" scoped>
.layout{
  height: calc(100vh - 88px);
  width: 100%;
  box-sizing: border-box;
  overflow-y: scroll;
  //border: 1px solid red;
  &::-webkit-scrollbar {
    display: none;
  }
  .content{
    width: 100%;
    .layout{
      width: 100%;
      height: calc(100% - 60px);
      .info{
        width: 100%;
        height: 50px;
        background-color: #3c9cff;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20px;
        color: #FFFFFF;
        box-sizing: border-box;
      }
      .title{
        margin-top: 15px;
        padding: 0 15px;
        width: 100%;
        box-sizing: border-box;
      }
      .size{
        margin-top: 15px;
        padding: 0 15px;
        box-sizing: border-box;
        .size-title{
          font-size: 14px;
          color: #333333;
        }
        .size-list{
          display: grid;
          margin-top: 10px;
          grid-template-columns: repeat(4, 1fr); /* 每行4个 box */
          gap: 10px; /* 可选：设置box之间的间距 */
          .box{
            height: 40px;
            border: 1px solid #999999;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .active{
            background-color: rgba(60, 156, 255, .2);
            border-color: #3c9cff;
            color: #3c9cff;
          }
        }
      }
    }
    .btn{
      display: flex;
      justify-content: space-between;
      padding: 0 15px;
      position: fixed;
      bottom: 0;
      width: 100%;
      box-sizing: border-box;
      height: 60px;
      background-color: #FFFFFF;
      align-items: center;
      border-top: 1px solid #E5E5E5;
    }
  }
}
</style>
